// pages/search/search.js
import {request} from "../../request/index.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goods: [],
    // 是否显示取消
    isFocus: false,
    value: "",
    SearchNo: false
  },
  timeId: -1,
  //输入框值改变就触发
  onInput(e) {
    const {value} = e.detail;
    //值不合法
    if (!value.trim()) {
      this.setData({
        isFocus: false
      });
      this.clearList();
      return;
    }
    this.setData({
      isFocus: true
    });
    //获取数据
    //清除定时器(防抖节流)
    clearTimeout(this.timeId);
    this.timeId = setTimeout(() => this.getData(value), 1000);
  },
  //发送请求的函数
  async getData(query) {
    const res = await request({
      url: "/goods/qsearch",
      data:{query}
    });
    if (res.data.message.length === 0) {
      this.setData({SearchNo: true});
    }
    this.setData({
      goods: res.data.message
    });
    //如果已经删除值,则清除结果
    this.clearList();
  },
  //取消清除
  onClear() {
    this.setData({
      isFocus: false,
      value: ""
    });
    this.clearList();
  },
  //清除延迟返回条件
  clearList() {
    if (this.data.isFocus === false) {
      this.setData({
        goods:[],
        SearchNo:false
      });
    };
  }
})